﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceApplication.Service.Plan;
using CommonLibrary.DataModel.Plan;
using OAclient.Models;
using OAclient.Common;
using System.Data;
using CommonLibrary.Common;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Service.Basic;
using OAclient.Filters;
using System.IO;

namespace OAclient.Controllers
{
    [VaildateLogin]
    [ExceptionFilter]
    [LoggerFilter]
    public class NotifyController : Controller
    {
        //
        // GET: /Notify/
        PlanService ps = new PlanService();
        BasicService bs = new BasicService();
        private const Int32 PageSize = 15;

        //通知栏目 滚动
        public ActionResult NotifyPartial()
        {
            var notifyEntity = ps.QueryLastNotify();
            if (notifyEntity == null) return null;

            ViewData["notify_content"] = Server.HtmlDecode(notifyEntity.notify_content);
            ViewData["notify_id"] = notifyEntity.notify_id;

            return View();
        }

        public ActionResult NotifyShowNew()
        {
            var notifyEntity = ps.QueryLastNotify();
            ViewData["notify_content"] = notifyEntity.notify_content;
            ViewData["notify_id"] = notifyEntity.notify_id;
            return View();
        }

        public ActionResult NotifyPreList(Int32 page)
        {
            var dt = ps.QueryAllNotify();
            var pageInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = 5,
                TotalItems = dt.Rows.Count
            };

            if (dt.Rows.Count > 0)
                dt = dt.AsEnumerable().Skip((page - 1) * 5).Take(5).CopyToDataTable<DataRow>();
            ViewData["notify_list"] = dt;
            ViewData["pageInfo"] = pageInfo;
            return PartialView("NotifyPreview");
        }

        //notify-1
        public ActionResult NotifyList(Int32 page, UserModel user)
        {

            var dt = ps.QueryAllNotify();

            var pageInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = dt.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;
            if (dt.Rows.Count > 0)
                dt = dt.AsEnumerable().Skip((page - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt"] = dt;
            return PartialView();
        }

        //notify-2
        public ActionResult NotifyListMng(Int32 page, UserModel user)
        {
            var dt = bs.QueryMsgByCodition(user.user.user_id, "", "", "", "", 0, null);

            var tmp = dt.Select("标题 like '企业公告%'");
            if (tmp.Length > 0)
                dt = tmp.CopyToDataTable();

            var pageInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = dt.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;
            if (dt.Rows.Count > 0)
                dt = dt.AsEnumerable().Skip((page - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt"] = dt;
            return PartialView();
        }


        //notify-3
        public ActionResult NotifyAdd(UserModel user)
        {
            ViewData["user_id"] = user.user.user_id;
            ViewData["appendix"] = ZTreeHelper.Serialize(getAppendixNodeList(user));
            return PartialView();
        }

        //notify-4
        public ActionResult NotifyModify(int msg_id)
        {

            MsgEntity msgEntity = bs.QueryMsg(msg_id);
            DataTable dt_msgmx = bs.QueryMsgmx(msg_id);

            ViewData["title"] = msgEntity.msg_titile;
            ViewData["content"] = Server.HtmlDecode(msgEntity.msg_content);
            ViewData["sendtime"] = msgEntity.msg_sendtime;
            UserEntity userEntity = bs.QueryUser(msgEntity.creater_id);
            ViewData["creater_id"] = userEntity.user_id;
            ViewData["creater_name"] = userEntity.user_name;
            var rootPath = produRootPath();
            var paths = CommonMethod.splitString(msgEntity.msg_appendix, ';');
            var files = String.Empty;
            foreach (var path in paths)
            {
                var fileName = path.Substring(path.LastIndexOf("/") + 1);
                var tmppath = HttpUtility.UrlEncode(path).ToLower();
                var tmpfilename = HttpUtility.UrlEncode(fileName).ToLower();
                files += "<a href='/Message/fileFromDisk?path=" + tmppath + "&fileName=" + tmpfilename + "'>" + fileName + "</a><br />";
            }
            ViewData["dt_msgmx"] = dt_msgmx;
            ViewData["msg_appendix"] = files;
            return PartialView();
        }
        //public ActionResult NotifyPreview()
        //{
        //    var dt = ps.QueryAllNotify();
        //    if (dt.Rows.Count > 0)
        //        dt = dt.AsEnumerable().Take(5).CopyToDataTable<DataRow>();
        //    ViewData["notify_list"] = dt;
        //    return PartialView();
        //}

        #region 方法

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DoNotifyAdd(string title, string content, string content2, string receiver_ids, string creater_id, string appendix)
        {
            if (string.IsNullOrEmpty(title))
                return Json(new ResTag(false, "标题不能为空"));

            //var dt = bs.QueryAllUsers();
            //var arr_ids = dt.AsEnumerable().Select(x => x.Field<int>("用户编码").ToString()).ToArray();
            //var str_ids = string.Join(",", arr_ids);
            MsgEntity msgEntity = new MsgEntity()
            {
                creater_id = int.Parse(creater_id),
                msg_content = content,
                msg_content2 = content2,
                msg_isread = "未读",
                msg_appendix = appendix,
                msg_lev = 0,
                msg_sendtime = DateUtil.getStandardTimeBySecond(),
                msg_titile = "企业公告-" + title,
                receiver_ids = receiver_ids,
                msg_appendix_name = "",
                msg_save = 0,
            };
            int msg_id = bs.AddMsg(msgEntity);

            NotifyEntity ne = new NotifyEntity()
            {
                creater_id = int.Parse(creater_id),
                notify_content = content,
                notify_content2 = content2,
                notify_createtime = DateUtil.getStandardTimeBySecond(),
                notify_descn = msg_id.ToString(),
                notify_title = "企业公告-" + title,
            };
            ps.AddNotify(ne);
            return Json(new ResTag(true));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DoNotifyModify(int notify_id, string notify_title, string notify_content)
        {
            if (string.IsNullOrEmpty(notify_title))
                return Json(new ResTag(false, "标题不能为空"));
            NotifyEntity ne = ps.QueryNotify(notify_id);
            ne.notify_title = notify_title;
            ne.notify_content = notify_content;
            ps.UpdateNotify(ne);
            return Json(new ResTag(true));
        }

        #region 获取附件

        private Node getAppendixNodeList(UserModel user)
        {
            var userId = user.user.user_id.ToString();
            var path = produRootPath();
            path = Path.Combine(path, userId);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            var node = new Node();
            var Nodes = getAppendixNode(node, path, user.user.user_id.ToString());
            if (Nodes.Nodes.Count == 0)
            {
                Nodes.Text = "无附件可供添加";
                Nodes.Value = "appendix";
            }
            else
            {
                Nodes.Text = "我的附件";
                Nodes.Value = "appendix";
            }
            return Nodes;
        }
        private String produRootPath()
        {
            var rootPath = Server.MapPath("/");
            rootPath = Path.Combine(rootPath, "WebStore");
            rootPath = Path.Combine(rootPath, "Person");
            return rootPath;
        }

        private Node getAppendixNode(Node rootNode, String path, String userId)
        {
            var list_userfile = bs.FilesQuery(userId);
            var rootPath = produRootPath();
            var dire = new DirectoryInfo(path);
            var files = dire.GetFiles();
            foreach (var file in files)
            {
                var filePath = file.FullName.Replace(rootPath, "");
                filePath = filePath.Replace("\\", "/");
                string filename = string.Empty;
                if (list_userfile.Count > 0 && list_userfile.Where(x => file.Name.Contains(x.file_replacename)).ToArray().Count() > 0)
                    filename = list_userfile.Where(x => file.Name.Contains(x.file_replacename)).ToArray()[0].file_name;
                rootNode.Nodes.Add(new Node
                {
                    Text = filename == "" ? file.Name : filename,
                    Value = filePath
                });
            }
            var dires = dire.GetDirectories();
            foreach (var dir in dires)
                getAppendixNode(rootNode, dir.FullName, userId);
            return rootNode;
        }

        #endregion
        #endregion
    }
}
